package cn.whb.hrm.config;

import cn.whb.hrm.authen.MyAuthenFailHandler;
import cn.whb.hrm.authen.MyAuthenSuccessHandler;
import cn.whb.hrm.service.MyUserDetail;
import cn.whb.hrm.smslogin.SmsCodeProvider;
import cn.whb.hrm.smslogin.SmsLoginAuthenticationFilter;
import cn.whb.hrm.smslogin.SmsLoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//security 的配置
@Configuration
@EnableWebSecurity  //开启Security
public class SmsAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private MyUserDetail myUserDetail ;

    @Autowired
    private MyAuthenFailHandler myAuthenFailHandler;

    @Autowired
    private MyAuthenSuccessHandler myAuthenSuccessHandler;

    @Override
    public  void configure(HttpSecurity http) throws Exception {

        //短信验证码登录=========================================================================================start
        //短信认证Filter
        SmsLoginAuthenticationFilter smsAuthFilter = new SmsLoginAuthenticationFilter();
        smsAuthFilter.setAuthenticationSuccessHandler(myAuthenSuccessHandler);
        smsAuthFilter.setAuthenticationFailureHandler(myAuthenFailHandler);

        smsAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //短信认证provider
        SmsCodeProvider smsCodeProvider = new SmsCodeProvider();
        smsCodeProvider.setUserDetailsService(myUserDetail);


        //添加短信认证provider
        http.authenticationProvider(smsCodeProvider);
        //添加短信认证filter
        http.addFilterAfter(smsAuthFilter, UsernamePasswordAuthenticationFilter.class);

        //短信验证码登录=========================================================================================end
    }
}